package com.cvte.boe.media;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.cvte.boe.media.adapter.RecyclerViewClickAndSelectAdapter;
import com.cvte.boe.media.adapter.UsbDevAdapter;
import com.cvte.boe.media.controller.MediaFileManager;
import com.cvte.boe.media.model.ExtraInfoModel;
import com.cvte.boe.media.model.LocalDeviceInfo;
import com.cvte.boe.media.utils.ComparatorUtil;
import com.cvte.boe.media.utils.DeviceDataUtils;
import com.cvte.boe.media.utils.LogUtil;
import com.cvte.boe.media.utils.MountAction;
import com.cvte.boe.media.utils.MountListUtil;
import com.cvte.boe.media.utils.OrientationUtil;
import com.cvte.boe.media.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MediaLocalDevMainActivity extends Activity implements RecyclerViewClickAndSelectAdapter.OnItemClickListener,RecyclerViewClickAndSelectAdapter.OnItemSelectListener{
    private final String TAG = MediaLocalDevMainActivity.this.getClass().getSimpleName();
    private static final int UPDATE_REFRESH = 0x1;
    private static final int UPDATE_MOUNT_START = 0x2;
    private static final int UPDATE_MOUNT_COMPLETE = 0x3;
    private static final int UPDATE_UNMOUNT = 0x4;
    private Context mContext;
    private RecyclerView rvUsbDev;
    private TextView tvNoUsbRemind;
    private MountAction mMountAction = null;
    private List<LocalDeviceInfo> mDevInfoList = new ArrayList();
    private UsbDevAdapter usbDevAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_usb_dev_main);
        mContext = this;

        MediaApplication.registerMountActionListener(mountActionListener);
        //INIT DATA
        mDevInfoList.clear();
        MountListUtil.getInstance().initMountInfoList();
        List<ExtraInfoModel> list = MountListUtil.getInstance().getExtraInfoList();
        for (int i = list.size() - 1; i >= 0; i--) {
            String mountPoint = list.get(i).getMountPoint();
            if (!mountPoint.endsWith(File.separator)) {
                mountPoint = mountPoint.concat(File.separator);
            }
            LocalDeviceInfo dto = DeviceDataUtils.getDeviceFromCmdDetail(mountPoint);
            if (dto != null) {
                ExtraInfoModel model = MountListUtil.getInstance().getExtraInfoModel(mountPoint);
                dto.setDevAlias(model != null ? model.getLabel() : "");
                DeviceDataUtils.getLocDevSizeByStatFs(mContext, dto);
                DeviceDataUtils.getLocDevName(dto);
                mDevInfoList.add(dto);
            }
        }
        Collections.sort(mDevInfoList,new ComparatorUtil.LocalDevComparator());
        //INIT VIEW
        rvUsbDev = (RecyclerView)findViewById(R.id.rv_usb_list);
        tvNoUsbRemind = (TextView)findViewById(R.id.tv_no_usb_remind);
        if(list.size() == 0 ){
            tvNoUsbRemind.setVisibility(View.VISIBLE);
        }
        LinearLayoutManager layoutManager;
        if(OrientationUtil.isLandscapeOrientation(mContext)){
            layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
        }else{
            layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        }
        rvUsbDev.setLayoutManager(layoutManager);
        usbDevAdapter = new UsbDevAdapter(mContext,mDevInfoList);
        usbDevAdapter.setOnItemClickListener(this);
        usbDevAdapter.setOnItemSelectListener(this);
        usbDevAdapter.setHasStableIds(true);
        rvUsbDev.setAdapter(usbDevAdapter);

        mMountAction = new MountAction(mContext);
        mMountAction.setMountListener(mMountListener);
        new Thread(mMountAction).start();
    }

    @Override
    protected void onDestroy() {
        mHandler.removeMessages(UPDATE_UNMOUNT);
        mHandler.removeMessages(UPDATE_MOUNT_START);
        mHandler.removeMessages(UPDATE_MOUNT_COMPLETE);
        mHandler.removeMessages(UPDATE_REFRESH);
        mHandler.removeCallbacksAndMessages(null);
        if(mMountAction != null) {
            mMountAction.stop();
        }
        MediaApplication.unRegisterMountActionListener(mountActionListener);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return false;
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message paramMessage) {
            switch (paramMessage.what) {
                case UPDATE_MOUNT_START:
                    LogUtil.d(TAG,"UPDATE_MOUNT_START");
                    if(mDevInfoList.size() == 0) {
                        tvNoUsbRemind.setVisibility(View.VISIBLE);
                    }
                    break;
                case UPDATE_MOUNT_COMPLETE:
                    LogUtil.d(TAG,"UPDATE_MOUNT_COMPLETE");
                    if(mDevInfoList.size() != 0) {
                        tvNoUsbRemind.setVisibility(View.GONE);
                    }
                    Collections.sort(mDevInfoList,new ComparatorUtil.LocalDevComparator());
                    usbDevAdapter.setLocalDevList(mDevInfoList);
                    usbDevAdapter.notifyDataSetChanged();
                    break;
                case UPDATE_UNMOUNT:
                    Bundle data = paramMessage.getData();
                    String path = data.getString("path");
                    if (path != null && path.startsWith("file://")) {
                        path = path.substring("file://".length());
                    }
                    for (int i = 0; i < mDevInfoList.size(); i++) {
                        LocalDeviceInfo info = mDevInfoList.get(i);
                        String mountPoint = info.getMountPath();
                        if (mountPoint.endsWith("/")) {
                            mountPoint = mountPoint.substring(0, mountPoint.length() - 1);
                        }
                        if (path.endsWith("/")) {
                            path = path.substring(0, mountPoint.length() - 1);
                        }
                        if (mountPoint.equals(path)) {
                            mDevInfoList.remove(i);
                            break;
                        }
                    }
                    Collections.sort(mDevInfoList,new ComparatorUtil.LocalDevComparator());
                    usbDevAdapter.setLocalDevList(mDevInfoList);
                    usbDevAdapter.notifyDataSetChanged();
                    if(mDevInfoList.size() == 0) {
                        tvNoUsbRemind.setVisibility(View.VISIBLE);
                    }
                    MediaFileManager.getInstance().removePathDirToMediaFilesMap(StringUtils.formatMountPointWithoutSeparator(path));
                    break;
                case UPDATE_REFRESH:
                    break;
                default:
                    break;
            }
        }
    };

    private MountAction.MountListener mMountListener = new MountAction.MountListener() {
        @Override
        public void onMountComplete(LocalDeviceInfo info) {
            mDevInfoList.add(info);
            mHandler.sendEmptyMessage(UPDATE_MOUNT_COMPLETE);
        }

        @Override
        public void onMountStart() {
            mHandler.sendEmptyMessage(UPDATE_MOUNT_START);
        }
    };
    MediaApplication.MountActionListener mountActionListener = new MediaApplication.MountActionListener() {
        @Override
        public void onReceive(String volumePath, boolean mount) {
            if (mount) {
                LogUtil.d(TAG, "mount " + volumePath);
                if (mMountAction != null) {
                    mMountAction.addMount(volumePath);
                }
            } else {
                // when is audio or video playing , devUpdate can't remove so fast
                LogUtil.d(TAG, "unmount " + volumePath);
                Bundle bundle = new Bundle();
                bundle.putString("path", volumePath);
                Message msg = mHandler.obtainMessage();
                msg.what = UPDATE_UNMOUNT;
                msg.setData(bundle);
                mHandler.sendMessageDelayed(msg, 200L);
            }
        }
    };

    @Override
    public void onItemClick(int position) {
        Intent intent = new Intent(mContext,MediaFileBrowserActivity.class);
        intent.putExtra(LocalDeviceInfo.DEVICE_COMPRESS_NAME,mDevInfoList.get(position).compress());
        mContext.startActivity(intent);
    }

    @Override
    public void onItemSelect(final int position) {
        if(position < mDevInfoList.size()) {
            usbDevAdapter.setFocusPositionMountPath(mDevInfoList.get(position).getMountPath());
            if(usbDevAdapter.getSelectPosition() != position) {
                usbDevAdapter.setSelectPosition(position);
                Handler handler = new Handler();
                Runnable r = new Runnable() {
                    public void run() {
                        usbDevAdapter.notifyDataSetChanged();
                    }
                };
                handler.post(r);
            }
        }
    }
}
